package cool.lichuan.project.system.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cool.lichuan.common.domain.*;
import cool.lichuan.common.util.*;
import cool.lichuan.project.system.dto.ConfigVO;
import cool.lichuan.project.system.dto.CustInfo;
import cool.lichuan.project.system.dto.HeaderInfo;
import cool.lichuan.project.system.service.VaccineService;
import jdk.nashorn.internal.runtime.regexp.joni.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;
import sun.misc.BASE64Decoder;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Slf4j
@Service
public class VaccineServiceImpl implements VaccineService {

    @Autowired
    private CustInfo custInfo;
    @Autowired
    private HeaderInfo headerInfo;

    @Autowired
    private HttpUtils httpUtils;

    private ConfigVO configVO = new ConfigVO();

    @PostConstruct
    public void initConfig() {
        configVO.setCookie(headerInfo.getCookie());
        configVO.setId(custInfo.getId());
        configVO.setPid(custInfo.getPid());
        configVO.setSignature(headerInfo.getSignature());
        configVO.setDate(custInfo.getDate());
    }


    private Map<String, Object> parm = new HashMap<>();


    @Override
    public Boolean testConnect() {
        try {
            String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=GetCustSubscribeDateDetail&pid=7&id=1921&scdate=2022-02-23";
            String response = getDateDetail(configVO);
            //String response = HttpUtil.request(url, HttpUtil.PARAM_TYPE_JSON, getCommonHeader(custInfo.getCookie()).toArray(new BasicHeader[0]));
            System.out.println("encode:" +  response);
            //解码
            String s1 = Base64Utils.encodeToString(HexString.hexStr2Str(response));
            String s = AESUtil.decryptString(Base64Utils.decode(s1.getBytes()), configVO.getSignature(), configVO.getIv());
            System.out.println("decode:" + s);
            //编码
            byte[] encryptResult = AESUtil.encrypt(s, configVO.getSignature(), configVO.getIv());
            String encryptResultStr = Hex.encodeHexString(encryptResult).toUpperCase(Locale.ROOT);
            System.out.println(encryptResultStr);
            return encryptResultStr.equals(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public String getSubList() {
        try {
            URL url = new URL("https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=UserSubcribeList");
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");

            httpConn.setRequestProperty("Host", "cloud.cn2030.com");
            httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
            httpConn.setRequestProperty("content-type", "application/json");
            httpConn.setRequestProperty("zftsl", "afd645c69919d94e4f639953c09cba09");
            httpConn.setRequestProperty("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/92/page-frame.html");

            httpConn.setRequestProperty("Cookie", "ASP.NET_SessionId=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NDU1MzMyNDcuNTc3NDg3NSwiZXhwIjoxNjQ1NTM2ODQ3LjU3NzQ4NzUsInN1YiI6IllOVy5WSVAiLCJqdGkiOiIyMDIyMDIyMjA4MzQwNyIsInZhbCI6InpqWStBUUlBQUFBUU16Z3pNemMzTldJNE9XSmxOMlppWWh4dmNYSTFielZNYTFWV2EzaG1VMVJxVld3d2R6Wk5PV28zUTJaTkFCeHZcclxuVlRJMldIUXdObmRuTFhORFVpMVJNa3hWZVhBM1ozWk9NbkpCRFRNMkxqRXhNaTR5TURVdU1USUFBQUFBQUFBQSJ9.28f-YkPX3MfeiSDtAjL-zesQQZBvgeYO2_zMvxTiego");

            InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                    ? httpConn.getInputStream()
                    : httpConn.getErrorStream();
            Scanner s = new Scanner(responseStream).useDelimiter("\\A");
            String response = s.hasNext() ? s.next() : "";
            System.out.println(response);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public String decodeDateDetail(String text) {
        try {
            String s1 = Base64Utils.encodeToString(HexString.hexStr2Str(text));
            String s = AESUtil.decryptString(Base64Utils.decode(s1.getBytes()), configVO.getSignature(), configVO.getIv());
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ConfigVO getConfig() {
        return configVO;
    }

    @Override
    public Object updateHeaderInfo(ConfigVO headerInfo) {

        configVO.setIv("1234567890000000");
        configVO.setSetCookie("Set-Cookie");
        if (ObjectUtil.isNotNull(headerInfo.getCookie())) {
            headerInfo.setCookie(headerInfo.getCookie());
            headerInfo.setSignature(getSignature(headerInfo.getCookie()));
            configVO.setCookie(headerInfo.getCookie());
            configVO.setSignature(getSignature(headerInfo.getCookie()));
        }
        if (ObjectUtil.isNotNull(headerInfo.getSignature())) {
            headerInfo.setSignature(headerInfo.getSignature());
            configVO.setSignature(headerInfo.getSignature());
        }
        if (ObjectUtil.isNotNull(headerInfo.getId())) {
            headerInfo.setId(headerInfo.getId());
            configVO.setId(headerInfo.getId());
        }
        if (ObjectUtil.isNotNull(headerInfo.getPid())) {
            headerInfo.setPid(headerInfo.getPid());
            configVO.setPid(headerInfo.getPid());
        }
        if (ObjectUtil.isNotNull(headerInfo.getDate())) {
            headerInfo.setDate(headerInfo.getDate());
            configVO.setDate(headerInfo.getDate());
        }

        return getUserInfo();
    }

    private String getSignature(String cookie) {

        try {
            String[] split = cookie.split("=");
            String[] split1 = split[1].split("\\.");
            String payload = split1[1].replace("\\r\\n","");
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] bytes = base64Decoder.decodeBuffer(payload);
            String s = new String(bytes);
            JSONObject jsonObject = JSONUtil.parseObj(s);
            byte[] vals = base64Decoder.decodeBuffer(String.valueOf(jsonObject.get("val")));
            String substring = new String(vals).substring(9, 25);
            return substring;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String seckillVaccine() {
        try {
            log.info("根据可约时间获取加密数据获得mxid，id【{}】，医院id【{}】当前预约的时间{}", custInfo.getPid(), custInfo.getId(), custInfo.getDate());
            String responseHex = getDateDetail(configVO);
            log.info("根据可约时间获取加密数据获得mxid接口疫苗响应，pid={},id={},res={}",  configVO.getPid(), configVO.getId(), responseHex);
            String bas = Base64Utils.encodeToString(HexString.hexStr2Str(responseHex));
            String plaintext = AESUtil.decryptString(Base64Utils.decode(bas.getBytes()), configVO.getSignature(), configVO.getIv());
            log.info("根据可约时间获取加密数据获得mxid接口疫苗响应，解密数据,pid={},id={},明文【{}】",  configVO.getPid(), configVO.getId(), plaintext);
            Map<String, Object> objectObjectMap = JsonUtil.toMap(plaintext);
            Object list = objectObjectMap.get("list");
            List<Map<String, Object>> list1 = JsonUtil.toList(list);
            if (!CollectionUtils.isEmpty(list1)) {
                Map<String, Object> map = list1.get(0);
                String mxid = (String) map.get("mxid");
                configVO.setMxid(mxid);
                log.info("可以发起直接预约的对象数据{}", configVO);
                CustInfo setCookieCust = this.getCaptcha(configVO);
                if (!StrUtil.isEmpty(setCookieCust.getCookie())) {
                    configVO.setCookie(setCookieCust.getCookie());
                    //TODO 考虑多个线程提交订单
                    String result = this.orderPost(configVO);
                    log.info("save20 预约结果response：[{}]", result);
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "预约失败";
        }

        return "预约失败";
    }






    /**
     * 提交预约订单
     * @Method : orderPost
     * @Description : 提交预约订单
     * @return java.lang.String
     * @author : chenchao
     * @CreateDate : 2022/2/18 17:49
     *
     */
    private String orderPost(ConfigVO configVO) throws Exception {
        parm.put("sex", 2);
        parm.put("cname", configVO.getCname());
        parm.put("mxid", configVO.getMxid());
        parm.put("date", configVO.getDate());
        parm.put("tel", configVO.getTel());
        parm.put("pid", configVO.getPid());
        parm.put("birthday", configVO.getBirthday());
        parm.put("idcard", configVO.getIdcard());
        parm.put("doctype", 1);
        parm.put("Ftime", 1);
        parm.put("guid", "");
        String curl = "https://cloud.cn2030.com/sc/api/User/OrderPost";
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        String json = JsonUtil.toString(parm);
        System.out.println("json = " + json);
        byte[] encryptResult = AESUtil.encrypt(json, configVO.getSignature(), configVO.getIv());
        String encryptResultStr = Hex.encodeHexString(encryptResult).toUpperCase(Locale.ROOT);
        encryptResultStr = encryptResultStr.toLowerCase();
        Header[] headers = ArrayUtil.toArray(buildHeader(), Header.class);
        String response = HttpUtil.postOrder(null, curl,
                HttpUtil.METHOD_POST,
                encryptResultStr, HttpUtil.PARAM_TYPE_JSON, headers, null
        );
        log.info("预约结果" + response + "时间" + custInfo.getDate());
        return "预约结果" + response + "时间" + custInfo.getDate();
    }


    /**
     * 重新生成Cookie&获取mxid
     * @Method : getCaptcha
     * @Description : 重新生成Cookie&获取mxid
     * @return cool.lichuan.project.system.dto.CustInfo
     * @author : chenchao
     * @CreateDate : 2022/2/18 17:48
     *
     */
    private CustInfo getCaptcha(ConfigVO configVO) {
        HttpResponse response = null;
        try {
//            Thread.sleep(1000);
                String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=GetCaptcha&mxid=" + configVO.getMxid();
            HttpClient client = HttpClientBuilder.create().build();
            log.info("发起预约之前的一步校验获得新的cookie【URL：{}】", url);
            HttpPost request = new HttpPost(url);
            RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
            RequestConfig localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT)
                    .build();
            request.setConfig(localConfig);
            request.setHeaders(buildHeader().toArray(new BasicHeader[0]));

            response = client.execute(request);
            log.info("发起预约之前的一步校验获得新的cookie;响应结果【{}】", response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Header[] headers = response.getAllHeaders();
        for (Header header : headers) {
            if (headerInfo.getSetCookie().equals(header.getName())) {
                custInfo.setCookie(header.getValue());
            }
        }
        return custInfo;
    }


    /**
     * 构建请求header
     * @Method : getCommonHeader
     * @Description : 构建请求header
     * @param newCookie:
     * @return java.util.List<org.apache.http.Header>
     * @author : chenchao
     * @CreateDate : 2022/2/18 17:48
     *
     */
    /**
     * 生成header
     * @return
     */
    public  List<Header> buildHeader(){
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat"));
        headers.add(new BasicHeader("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/92/page-frame.html"));
        headers.add(new BasicHeader("zftsl", "e77d1ae14d5e6049df3dd896505bf335"));
        headers.add(new BasicHeader("Accept","application/json, text/plain, */*"));
        headers.add(new BasicHeader("Host","cloud.cn2030.com"));
        headers.add(new BasicHeader("Accept-Encoding","gzip, deflate, br"));
        headers.add(new BasicHeader("Cookie", configVO.getCookie()));
        headers.add(new BasicHeader("Connection", "keep-alive"));
        headers.add(new BasicHeader("content-type", "application/json"));
        return headers;
    }





















    public String  getDateDetail (ConfigVO configVO) {
        try {
            String reqUrl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=GetCustSubscribeDateDetail&pid=" + configVO.getPid() + "&id=" + configVO.getId() + "&scdate=" + configVO.getDate();
            URL url = new URL(reqUrl);
            System.out.println(reqUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            buildHeader(httpConn);
            InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                    ? httpConn.getInputStream()
                    : httpConn.getErrorStream();
            Scanner s = new Scanner(responseStream).useDelimiter("\\A");
            String response = s.hasNext() ? s.next() : "";
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String  getChaptcha()  {
        try {
            URL url = new URL("https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=GetCaptcha&mxid=zjY-AVpYAABAiTQB");
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");

            buildHeader(httpConn);

            InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                    ? httpConn.getInputStream()
                    : httpConn.getErrorStream();
            Scanner s = new Scanner(responseStream).useDelimiter("\\A");
            String response = s.hasNext() ? s.next() : "";
            System.out.println(response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String  orderPost() {
        try {
            URL url = new URL("https://cloud.cn2030.com/sc/api/User/OrderPost");
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");

            buildHeader(httpConn);

            httpConn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
            writer.write("a7ced95868ce854cecf81c88b2de7ed41e70bd9bf56b1aa8f7daf4b2606ce06b9e3a4fa29397b6802ef47d2c89359a2162b87d992288b04b6a702e2c3d0a5ba4197815a36562fa940070ea658f84d4b0dae303618859185027c87984b4d41383b973a453aa3f2b4d849b8c0124c9805eabaf90baafcd0231f29b8cc1e2fd9fb83c0986cfa88db6acdfd2bb31780e1d9e44865d11851de62da249267af2d8342cf38b32950b51705e6a38b486301dea1674ad2e6771475f4c00dc65c345cc5461");
            writer.flush();
            writer.close();
            httpConn.getOutputStream().close();

            InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                    ? httpConn.getInputStream()
                    : httpConn.getErrorStream();
            Scanner s = new Scanner(responseStream).useDelimiter("\\A");
            String response = s.hasNext() ? s.next() : "";
            System.out.println(response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public String  getOrderStatus()  {
        try {
            URL url = new URL("https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=GetOrderStatus");
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");

            buildHeader(httpConn);
            InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                    ? httpConn.getInputStream()
                    : httpConn.getErrorStream();
            Scanner s = new Scanner(responseStream).useDelimiter("\\A");
            String response = s.hasNext() ? s.next() : "";
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object  getUserInfo() {
        try {
            URL url = new URL("https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=User");
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");

            buildHeader(httpConn);

            InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                    ? httpConn.getInputStream()
                    : httpConn.getErrorStream();
            Scanner s = new Scanner(responseStream).useDelimiter("\\A");
            String response = s.hasNext() ? s.next() : "";
            System.out.println(response);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            JSONObject user = jsonObject.getJSONObject("user");
            ConfigVO configVOTemp = JSONUtil.toBean(user, ConfigVO.class);
            configVO.setCname(configVOTemp.getCname());
            configVO.setIdcard(configVOTemp.getIdcard());
            configVO.setSex(configVOTemp.getSex());
            configVO.setTel(configVOTemp.getTel());
            configVO.setBirthday(configVOTemp.getBirthday());
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    void buildHeader(HttpURLConnection httpConn) {
        httpConn.setRequestProperty("Host", "cloud.cn2030.com");
        httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
        httpConn.setRequestProperty("content-type", "application/json");
        httpConn.setRequestProperty("zftsl", getZftsl());
        httpConn.setRequestProperty("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/92/page-frame.html");
        httpConn.setRequestProperty("Cookie", configVO.getCookie());
    }

    private static String getZftsl() {
        //return DigestUtils.md5Hex("zfsw_" + System.currentTimeMillis() / 10000);
        //String date = String.valueOf((System.currentTimeMillis()) / 1000);
        //return md5("zfsw_" + date.substring(0, date.length() - 1));
        //
        return md5("zfsw_" + (System.currentTimeMillis() / 10000));
    }
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }



    public void checkDate() throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("city.json");
        String json = StreamUtils.copyToString(classPathResource.getInputStream(), Charset.defaultCharset());
        JSONObject a = JSONUtil.parseObj(json);
        File f = new File("C:\\Users\\Administrator\\Desktop\\疫苗抢购\\可预约数据.txt");
        FileOutputStream fos1 = new FileOutputStream(f);
        OutputStreamWriter dos1 = new OutputStreamWriter(fos1);
        StringBuilder stringBuilder = new StringBuilder();

        String[] province = {"河南","广东","河南","四川","安徽省","福建省","江苏省","湖北省","山东省","贵州省","山东省","湖南省"};
        //String[] province = {"甘肃省"};
        for (String provinceName : province) {
            ArrayList<City> cities = new ArrayList<>();
            for (Map.Entry<String, Object> stringObjectEntry : a.entrySet()) {
                String key = stringObjectEntry.getKey();
                JSONObject jsonObject = (JSONObject) a.get(key);
                for (Map.Entry<String, Object> objectEntry : jsonObject.entrySet()) {
                    JSONObject strictCity = (JSONObject) objectEntry.getValue();
                    JSONObject parent = (JSONObject) strictCity.get("parent");
                    if (parent.containsKey("level") && parent.get("level").equals("city")) {
                        if (parent.containsKey("name")) {
                            JSONObject parent1 = (JSONObject) parent.get("parent");
                            if (String.valueOf(parent1.get("name")).contains(provinceName)) {

                                String name = "[\"" + parent1.get("name") + "\",\"" + parent.get("name") + "\"]";
                                String name1 = URLEncoder.encode(URLEncoder.encode((String) parent.get("name"), "UTF-8"), "UTF-8");
                                String center = (String) parent.get("center");
                                String[] split = center.split(",");
                                cities.add(JSONUtil.toBean(parent, City.class));
                                continue;
                            }



                        }
                    }
                }

            }
            //去重
            List<City> collect = cities.stream().filter(distinctByKey(City::getName)).collect(Collectors.toList());

            for (City city : collect) {
                String[] split = city.getCenter().split(",");
                String name = "[\""+city.getParent().getName()+"\",\""+city.getName()+"\"]";

                String targetUrl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=CustomerList&city=" + name + "&lat=" + split[1] + "&lng=" + split[0] + "&id=0&cityCode=" + city.getAdcode() + "&product=27";
                //String targetUrl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=CustomerList&city=%5B%22%E6%B2%B3%E5%8D%97%E7%9C%81%22%2C%22%E9%83%91%E5%B7%9E%E5%B8%82%22%2C%22%22%5D&lat=39.72684&lng=116.34159&id=0&cityCode=410100&product=1";
                URL url = new URL(targetUrl);

                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setRequestMethod("GET");

                httpConn.setRequestProperty("Host", "cloud.cn2030.com");
                httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
                httpConn.setRequestProperty("content-type", "application/json");
                httpConn.setRequestProperty("zftsl", "b18a5a4eb138206200a7bb7da592febc");
                httpConn.setRequestProperty("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/92/page-frame.html");

                httpConn.setRequestProperty("Cookie", "ASP.NET_SessionId=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NDY4NzcxNjUuMjk0Njg1MSwiZXhwIjoxNjQ2ODgwNzY1LjI5NDY4NTEsInN1YiI6IllOVy5WSVAiLCJqdGkiOiIyMDIyMDMxMDA5NTI0NSIsInZhbCI6ImFhWkNBUUlBQUFBUU5HWmpPVEJrWmpZeVlXUTNaRGxsWWh4dmNYSTFielZNYTFWV2EzaG1VMVJxVld3d2R6Wk5PV28zUTJaTkFCeHZcclxuVlRJMldIUXdObmRuTFhORFVpMVJNa3hWZVhBM1ozWk9NbkpCRFRFeU15NHhNVGd1TnpndU16UUFBQUFBQUFBQSJ9.K5IvtfXIyzOjH4qVUBJ2_sSNaAv-Xy_Ms939rr9avCo");

                InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                        ? httpConn.getInputStream()
                        : httpConn.getErrorStream();
                Scanner s = new Scanner(responseStream).useDelimiter("\\A");
                String response = s.hasNext() ? s.next() : "";
                HospitalResponse hospitalResponse = JSONUtil.toBean(response, HospitalResponse.class);
                Thread.sleep(100);
                List<HospitalList> list = hospitalResponse.getList();
                for (HospitalList hospitalList : list) {
                    String detailUrl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=CustomerProduct&id=" + hospitalList.getId() + "&lat=" + hospitalList.getLat() + "&lng=" + hospitalList.getLat();
                    HttpGet httpGet = new HttpGet(detailUrl );
                    String result = httpUtils.doRequest(httpGet);
                    DetailResponse detailResponse = JSONUtil.toBean(result, DetailResponse.class);
                    List<VaccineList> vaccineLists = detailResponse.getList();
                    Thread.sleep(100);
                    for (VaccineList vaccineList : vaccineLists) {
                        //九价
                        if (vaccineList.getId() == 1 ||vaccineList.getId() == 2) {
                            if (vaccineList.getDate().length() > 4) {
                                String msg = city.getParent().getName() + "->" + city.getName() + "->" + hospitalList.getCname() + ":\t" + "存在可预约:" + vaccineList.getText() + "\t 预约日期:" + vaccineList.getDate() + "\r\n";
                                System.err.println(msg );
                                stringBuilder.append(msg);
                            } else {
                                System.out.println(city.getParent().getName() + "->" + city.getName() + "->" + hospitalList.getCname() +":\t" + "无可预约疫苗");
                            }
                        }
                    }

                }

            }
        }


        dos1.write(stringBuilder.toString());
        dos1.close();

    }

    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }







}
